package edu.cth.speedapp.asynctasks;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;

public class HTTPAsyncTask extends AsyncTask<String, String, String>{

	private ITaskCallback callback;
	
	public HTTPAsyncTask(ITaskCallback callback) {
		super();
		this.callback = callback; 
	}
	
	@Override
	protected String doInBackground(String... params) {	
		
	HttpClient httpclient = new DefaultHttpClient();
	HttpResponse response;
	String result = null;
	try {
	    response = httpclient.execute(new HttpGet(params[0]));
	    StatusLine statusLine = response.getStatusLine();
	    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
	        ByteArrayOutputStream out = new ByteArrayOutputStream();
	        response.getEntity().writeTo(out);
	        out.close();
	        result = out.toString();
	        
	    } else{
	        //Closes the connection.
	        response.getEntity().getContent().close();
	        throw new IOException(statusLine.getReasonPhrase());
	    }
	} catch (ClientProtocolException e) {
	    result = "ClientProtocolException";
	} catch (IOException e) {
		result = "IOException" + e.getStackTrace();
	}

		return result;
	}

	@Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        callback.httpTaskCallback(result);
    }

	
}
